package cn.hfatec.shms.web.qz.qzActual.service;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.HashMap;


import cn.hfatec.shms.cache.CodeInfoCache;
import cn.hfatec.shms.enums.CodeType;
import cn.hfatec.shms.system.codeInfo.model.CodeInfo;
import cn.hfatec.shms.web.cw.cwChtb.model.CwChtb;
import cn.hfatec.shms.web.cw.cwChtb.model.CwChtbParams;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hfatec.base.BaseDao;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.shms.web.qz.qzActual.model.QzActual;
import cn.hfatec.shms.web.qz.qzActual.dao.QzActualDao;
import cn.hfatec.shms.web.qz.qzActual.model.QzActualParams;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author hfatec
 * @version 1.0
 *          <p/>
 *          the JAVA code is generate by middlegen
 */
@Service("QzActualService")
public class QzActualService {

    public static final String BEAN_ID = "QzActualService";

    //注入Dao层
    @Resource(name = "QzActualDao")
    private QzActualDao qzActualDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    @Transactional
    public static String encodeFilename(HttpServletRequest request, String fileName) {
        String rtn = "";
        try {
            String userAgent = request.getHeader("USER-AGENT");
            String new_filename = URLEncoder.encode(fileName, "UTF8");

            rtn = "filename=\"" + new_filename + "\"";

            if (userAgent != null) {
                userAgent = userAgent.toLowerCase();

                if (userAgent.indexOf("msie") != -1) {
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("opera") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                } else if (userAgent.indexOf("safari") != -1) {
                    rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"";
                } else if (userAgent.indexOf("applewebkit") != -1) {
                    new_filename = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
                    rtn = "filename=\"" + new_filename + "\"";
                } else if (userAgent.indexOf("mozilla") != -1) {
                    rtn = "filename*=UTF-8''" + new_filename;
                }
            }
        } catch (UnsupportedEncodingException e) {
            try {
                rtn = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } catch (UnsupportedEncodingException localUnsupportedEncodingException1) {
            }
        }
        return rtn;
    }

    /**
     * 查询数据
     *
     * @param qzActualParams
     * @param page
     */
    @Transactional
    public Table queryQzActualTable(QzActualParams qzActualParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", qzActualParams);
        return baseDao.queryTableByPage("queryQzActual", params, page);
    }

    /**
     * 查询李组数据
     *
     * @param qzActualParams
     * @param page
     */
    @Transactional
    public Table queryQzLzTable(QzActualParams qzActualParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", qzActualParams);
        return baseDao.queryTableByPage("queryQzLz", params, page);
    }

    /**
     * 查询叶组数据
     *
     * @param qzActualParams
     * @param page
     */
    @Transactional
    public Table queryQzYzTable(QzActualParams qzActualParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", qzActualParams);
        return baseDao.queryTableByPage("queryQzYz", params, page);
    }

    /**
     * 查询洪组数据
     *
     * @param qzActualParams
     * @param page
     */
    @Transactional
    public Table queryQzHzTable(QzActualParams qzActualParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", qzActualParams);
        return baseDao.queryTableByPage("queryQzHz", params, page);
    }

    /**
     * 查询翁组数据
     *
     * @param qzActualParams
     * @param page
     */
    @Transactional
    public Table queryQzWzTable(QzActualParams qzActualParams, Page page) {

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", qzActualParams);
        return baseDao.queryTableByPage("queryQzWz", params, page);
    }

    /**
     * 根据ID获取数据
     *
     * @param id
     */
    @Transactional
    public QzActual getQzActual(Integer id) {

        return qzActualDao.getQzActualById(id);
    }

    /**
     * 导出
     *
     * @param
     */
    @Transactional
    public String exportExcel(QzActualParams qzActualParams, HttpServletRequest request, HttpServletResponse response) {
        try {
            String clientFileName = encodeFilename(request, System.currentTimeMillis() + "");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; " + clientFileName + ".xls");
            response.setContentType("application/octet-stream;charset=UTF-8");
            OutputStream os = response.getOutputStream();
            String sign=qzActualParams.getSign();
            List dataList;
            if (sign.equals("1")) {
                dataList = qzActualDao.queryQzActual(qzActualParams);
            } else if (sign.equals("2")) {
                dataList = qzActualDao.queryQzLz(qzActualParams);
            } else if (sign.equals("3")) {
                dataList = qzActualDao.queryQzYz(qzActualParams);
            } else if (sign.equals("4")) {
                dataList = qzActualDao.queryQzHz(qzActualParams);
            } else {
                dataList = qzActualDao.queryQzWz(qzActualParams);
            }
            List nameList = new ArrayList();
            Calendar c = Calendar.getInstance();
            int weeknum = c.get(Calendar.WEEK_OF_YEAR);
            nameList.add("大类");
            nameList.add("中类");
            nameList.add("小类");
            nameList.add("合计");
            int weekmoth = 0;
            for (int i = 12; i >= 0; i--) {
                weekmoth = (weeknum - i) % 13;
                if (weekmoth == 0) {
                    weekmoth = 13;
                }
                nameList.add("Q" + (int) Math.floor((weeknum - i + 12) / 13) + "WK" + String.valueOf(weekmoth));
            }

            this.exportExcel(nameList, dataList, os);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @return HSSFWorkbook
     */
    public HSSFWorkbook createWorkbook(List fieldName, List fieldData) {
        List<CodeInfo> sexList = CodeInfoCache.getCodeInfo(CodeType.SEX);

        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("经营评估");
        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

        HSSFCellStyle cellstyle = (HSSFCellStyle) wb.createCellStyle();// 设置表头样式
        cellstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
        cellstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 设置水平居中
        cellstyle.setWrapText(true); // 设置为自动换行
        HSSFFont cellFont = (HSSFFont) wb.createFont(); // 创建表头字体样式
        cellFont.setFontHeightInPoints((short) 10); // 设置字体大小
        cellFont.setFontName("宋体"); // 设置字体类型
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
        cellstyle.setFont(cellFont); // 为表头样式设置字体样式


        for (int i = 0; i < fieldName.size(); i++) {
            HSSFCell cell = row.createCell((short) i);
            cell.setCellValue((String) fieldName.get(i));
            cell.setCellStyle(cellstyle);
        }

        QzActual qzActual = null;

        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        for (int i = 0; i < fieldData.size(); i++) {
            row = sheet.createRow(i + 1);
            qzActual = (QzActual) fieldData.get(i);
            // 第四步，创建单元格，并设置值

            if (qzActual.getLarge() == null) {
                row.createCell((short) 0).setCellValue("");
            } else {
                row.createCell((short) 0).setCellValue(qzActual.getLarge());
            }
            if (qzActual.getMedium() == null) {
                row.createCell((short) 1).setCellValue("");
            } else {
                row.createCell((short) 1).setCellValue(qzActual.getMedium());
            }
            if (qzActual.getSmall() == null) {
                row.createCell((short) 2).setCellValue("");
            } else {
                row.createCell((short) 2).setCellValue(qzActual.getSmall());
            }

            if (qzActual.getTotal() == null) {
                row.createCell((short) 3).setCellValue("");
            } else {
                row.createCell((short) 3).setCellValue(qzActual.getTotal());
            }
            if (qzActual.getWk1() == null) {
                row.createCell((short) 4).setCellValue("");
            } else {
                row.createCell((short) 4).setCellValue(qzActual.getWk1());
            }
            if (qzActual.getWk2() == null) {
                row.createCell((short) 5).setCellValue("");
            } else {
                row.createCell((short) 5).setCellValue(qzActual.getWk2());
            }
            if (qzActual.getWk3() == null) {
                row.createCell((short) 6).setCellValue("");
            } else {
                row.createCell((short) 6).setCellValue(qzActual.getWk3());
            }
            if (qzActual.getWk4() == null) {
                row.createCell((short) 7).setCellValue("");
            } else {
                row.createCell((short) 7).setCellValue(qzActual.getWk4());
            }
            if (qzActual.getWk5() == null) {
                row.createCell((short) 8).setCellValue("");
            } else {
                row.createCell((short) 8).setCellValue(qzActual.getWk5());
            }
            if (qzActual.getWk6() == null) {
                row.createCell((short) 9).setCellValue("");
            } else {
                row.createCell((short) 9).setCellValue(qzActual.getWk6());
            }
            if (qzActual.getWk7() == null) {
                row.createCell((short) 10).setCellValue("");
            } else {
                row.createCell((short) 10).setCellValue(qzActual.getWk7());
            }
            if (qzActual.getWk8() == null) {
                row.createCell((short) 11).setCellValue("");
            } else {
                row.createCell((short) 11).setCellValue(qzActual.getWk8());
            }
            if (qzActual.getWk9() == null) {
                row.createCell((short) 12).setCellValue("");
            } else {
                row.createCell((short) 12).setCellValue(qzActual.getWk9());
            }
            if (qzActual.getWk10() == null) {
                row.createCell((short) 13).setCellValue("");
            } else {
                row.createCell((short) 13).setCellValue(qzActual.getWk10());
            }
            if (qzActual.getWk11() == null) {
                row.createCell((short) 14).setCellValue("");
            } else {
                row.createCell((short) 14).setCellValue(qzActual.getWk11());
            }
            if (qzActual.getWk12() == null) {
                row.createCell((short) 15).setCellValue("");
            } else {
                row.createCell((short) 15).setCellValue(qzActual.getWk12());
            }
            if (qzActual.getWk13() == null) {
                row.createCell((short) 16).setCellValue("");
            } else {
                row.createCell((short) 16).setCellValue(qzActual.getWk13());
            }
        }
        //自适应列宽
        for (int i = 0; i < fieldName.size(); i++) {
            sheet.autoSizeColumn((short) i);
        }
        return wb;
    }

    //将信息写入输出流的方法。
    public void exportExcel(List fieldName, List fieldData, OutputStream os) throws Exception {
        HSSFWorkbook wb = createWorkbook(fieldName, fieldData);
        wb.write(os);
        os.close();
    }
}